package cn.rongcloud.im.server;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.List;

import cn.rongcloud.im.server.network.http.HttpException;
import cn.rongcloud.im.server.network.http.SyncHttpClient;
import cn.rongcloud.im.server.utils.json.JsonMananger;


/**
 * Created by AMing on 16/1/14.
 * Company RongCloud
 */
public class BaseAction {

    public static final String DOMAIN = "http://service.jiangaifen.com:38082";
    protected Context mContext;
    protected SyncHttpClient httpManager;
    protected String mHeadToken;


    /**
     * 构造方法
     *
     * @param context 上下文
     */
    public BaseAction(Context context) {
        this.mContext = context;
        this.httpManager = SyncHttpClient.getInstance(context);
        this.mHeadToken = getToken(context);
    }

    /**
     * JSON转JAVA对象方法
     *
     * @param json json
     * @param cls  class
     * @throws HttpException
     */
    public <T> T jsonToBean(String json, Class<T> cls) throws HttpException {
        return JsonMananger.jsonToBean(json, cls);
    }

    /**
     * JSON转JAVA数组方法
     *
     * @param json json
     * @param cls  class
     * @throws HttpException
     */
    public <T> List<T> jsonToList(String json, Class<T> cls) throws HttpException {
        return JsonMananger.jsonToList(json, cls);
    }

    /**
     * JAVA对象转JSON方法
     *
     * @param obj object
     * @throws HttpException
     */
    public String BeanTojson(Object obj) throws HttpException {
        return JsonMananger.beanToJson(obj);
    }


    /**
     * 获取完整URL方法
     *
     * @param url url
     */
    protected String getURL(String url) {
        return getURL(url, new String[]{});
    }

    /**
     * 获取完整URL方法
     *
     * @param url    url
     * @param params params
     */
    protected String getURL(String url, String... params) {
        StringBuilder urlBuilder = new StringBuilder(DOMAIN).append("/").append(url);
        if (params != null) {
            for (String param : params) {
                if (!urlBuilder.toString().endsWith("/")) {
                    urlBuilder.append("/");
                }
                urlBuilder.append(param);
            }
        }
        return urlBuilder.toString();
    }

    /**
     * 多个id转string，用逗号(,)分隔
     *
     * @param ids
     * @return
     */
    public String getIds(List<String> ids) {
        if (ids != null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < ids.size(); i++) {
                sb.append(ids.get(i));
                if (i + 1 < ids.size())
                    sb.append(",");
            }
            return sb.toString();
        }
        return null;
    }

    /**
     * @param context
     * @return
     */
    public String getToken(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("config", 0);
        return sharedPreferences.getString("mbtToken", (String) null);
    }
}
